package com.gem.util;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**JDBC基础工具类*/
public class JdbcUtil {

	private static Properties prop;

	//静态代码块初始化属性类型
	static {
		try {
			prop = new Properties();
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconfig.properties");
			prop.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取连接
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(prop.getProperty("jdbc.driver"));
		String url = prop.getProperty("jdbc.url");
		String username = prop.getProperty("jdbc.username");
		String password = prop.getProperty("jdbc.password");
		return DriverManager.getConnection(url, username, password);
	}

	/**
	 * 资源释放
	 */
	public static void close(Connection conn, Statement pst) {
		if (pst != null) {
			try {
				pst.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection conn, Statement pst, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		close(conn, pst);
	}
}
